#!/bin/bash
# 
# Developed by Fred Weinhaus 7/7/2014 .......... revised 7/20/2015
# 
# ------------------------------------------------------------------------------
# 
# Licensing:
# 
# Copyright © Fred Weinhaus
# 
# My scripts are available free of charge for non-commercial use, ONLY.
# 
# For use of my scripts in commercial (for-profit) environments or 
# non-free applications, please contact me (Fred Weinhaus) for 
# licensing arrangements. My email address is fmw at alink dot net.
# 
# If you: 1) redistribute, 2) incorporate any of these scripts into other 
# free applications or 3) reprogram them in another scripting language, 
# then you must contact me for permission, especially if the result might 
# be used in a commercial or for-profit environment.
# 
# My scripts are also subject, in a subordinate manner, to the ImageMagick 
# license, which can be found at: http://www.imagemagick.org/script/license.php
# 
# ------------------------------------------------------------------------------
# 
####
#

hash1="$1"
hash2="$2"

# syntax: phashcompare "hash1" "hash2"

# test for correct number of digits (including newline)
num1=`echo "$hash1" | wc -m | sed 's/ *//g'`
num2=`echo "$hash2" | wc -m | sed 's/ *//g'`

# test for correct number of values
if [ $num1 -ne 169 ]; then
	echo "--- Number of First Hash Digits ($num1) is Incorrect --- "
	exit 1
fi
if [ $num2 -ne 169 ]; then
	echo "--- Number of Second Hash Digits ($num2) is Incorrect --- "
	exit 1
fi


# unhash the 168 digits into 42 floats
# split the 168 digits into array of 4 digits for each element, then divide by 100 and keep 2 decimal
arr1=(`echo $hash1 | fold -w 4`)
for ((i=0; i<42; i++)); do
array1[$i]=`echo "scale=2; ${arr1[$i]}/100" | bc`
done

arr2=(`echo "$hash2" | fold -w 4`)
for ((i=0; i<42; i++)); do
array2[$i]=`echo "scale=2; ${arr2[$i]}/100" | bc`
done


#echo "recovered phash1 values=${array1[*]}"
num1="${#array1[*]}"

#echo "recovered phash2 values=${array2[*]}"
num2="${#array2[*]}"

# test for correct number of values
if [ $num1 -ne 42 ]; then
	echo "--- Number of First Phash Values ($num1) is Incorrect --- "
	exit 1
fi
if [ $num2 -ne 42 ]; then
	echo "--- Number of Second Phash Values ($num2) is Incorrect --- "
	exit 1
fi


# compute sum squared differences of corresponding array values
ssd=0
for ((i=0; i<42; i++)); do
	pairArr[$i]="${array1[$i]},${array2[$i]}"
done
ssd=`echo ${pairArr[*]} | awk ' BEGIN { FS = ","; RS = " "; } { ssd+=($1-$2)*($1-$2); } END { print ssd; } '`

# report metric value
echo "$ssd"


